package com.ruoyi.dynamic.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.CommonUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.date.DateUtils;
import com.ruoyi.common.utils.parameter.DistanceUtil;
import com.ruoyi.dynamic.domain.UserDynamic;
import com.ruoyi.dynamic.domain.UserParty;
import com.ruoyi.dynamic.domain.UserPartyEnroll;
import com.ruoyi.dynamic.mapper.UserDynamicMapper;
import com.ruoyi.dynamic.mapper.UserPartyEnrollMapper;
import com.ruoyi.dynamic.mapper.UserPartyMapper;
import com.ruoyi.dynamic.pojo.AppDynamic;
import com.ruoyi.dynamic.pojo.AppParty;
import com.ruoyi.dynamic.pojo.AppUserDynamicVO;
import com.ruoyi.dynamic.service.AppDynamicService;
import com.ruoyi.framework.security.auth.JWTUser;
import com.ruoyi.framework.security.auth.RequestContext;
import com.ruoyi.system.domain.PriceSetting;
import com.ruoyi.system.service.IPriceSettingService;
import com.ruoyi.thread.TaskAsync;
import com.ruoyi.user.domain.FileAttachment;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.mapper.FileAttachmentMapper;
import com.ruoyi.user.mapper.UserMapper;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class AppDynamicServiceImpl implements AppDynamicService {

	@Autowired
	private UserDynamicMapper userDynamicMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private TaskAsync taskAsync;
	@Autowired
	private UserPartyMapper userPartyMapper;
	@Autowired
	private UserPartyEnrollMapper userPartyEnrollMapper;
	@Autowired
	private IPriceSettingService priceSettingService;
	@Autowired
	private FileAttachmentMapper fileAttachmentMapper;

	/**
	 * 	获取用户ID
	 * @return
	 */
	public Long getUserId() {
		Object object = RequestContext.get("userInfo");
		if(null == object) {
			return null;
		}
		JWTUser jwtUser = (JWTUser) object;
		if(null == jwtUser || null == jwtUser.getId()) {
			return null;
		}
		return jwtUser.getId();
	}

	@Override
	public AjaxResult userDynamic(AppUserDynamicVO param) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User currUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
				.select(User::getId,User::getLoginPointX,User::getLoginPointY,User::getEnabled));
		if(null == currUser) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(2 == currUser.getEnabled()) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			param.setLoginUserId(loginUserId);
			param.setLongitude(currUser.getLoginPointX()==null?new BigDecimal("112"):currUser.getLoginPointX());
			param.setLatitude(currUser.getLoginPointY()==null?new BigDecimal("28"):currUser.getLoginPointY());
			IPage<AppDynamic> userDynamic = userDynamicMapper.userDynamic(new Page<AppDynamic>().setCurrent(param.getPageNo()).setSize(10),param);
			List<AppDynamic> dynamicList = userDynamic.getRecords();
			dynamicList.parallelStream().forEach(dynamic ->{
				//处理关注状态
				if(null != param.getUserId()) {
					if(loginUserId.longValue() == param.getUserId().longValue()) {
						dynamic.setConcernStatus(-1);
					}
				}
				// 处理年龄
				if(null != dynamic.getBirthday()) {
					dynamic.setAge(CommonUtil.getAge(dynamic.getBirthday()));
				}else {
					dynamic.setAge(22);
				}
				//处理日期
				dynamic.setCreateTimeShow(DateUtils.getTimeCompareStringDynamic(dynamic.getCreateTime()));
				if(2 == param.getDynamicType()) {
					dynamic.setCreateTimeShow(DateUtils.getTimeCompareStringDynamicYmd(dynamic.getCreateTime()));
				}
				// 09-02 去掉约玩动态时间
				dynamic.setCreateTimeShow("");
				if(StringUtils.isNotEmpty(dynamic.getImg())) {
					dynamic.setImgNum(dynamic.getImg().split(",").length);
				}
				// 处理距离
				dynamic.setDistanceShow((DistanceUtil.transferDistance(
						dynamic.getDistance()==null?new BigDecimal("0").doubleValue():dynamic.getDistance().doubleValue())));
				// 处理虚拟用户距离
				if(3 == dynamic.getEnabled()) {
					if(dynamic.getVirtuallyDistance() > 0) {
						dynamic.setDistanceShow(dynamic.getVirtuallyDistance()+"km");
					}else {
						dynamic.setDistanceShow(DistanceUtil.getVirtuallyDistance());
					}
				}
				dynamic.setDistanceShow("");
				// 相册
				List<FileAttachment> fileList = fileAttachmentMapper.selectList(new LambdaQueryWrapper<FileAttachment>()
						.eq(FileAttachment::getFileModule, "photo").eq(FileAttachment::getUserId, dynamic.getUserId()));
				if(CollectionUtil.isNotEmpty(fileList)) {
					dynamic.setRealPersonAuth(1);
				}
			});
			taskAsync.updateUserStatus(loginUserId);
			return AjaxResult.success(CollectionUtil.isEmpty(dynamicList)?new ArrayList<AppDynamic>():dynamicList);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult publishDynamic(UserDynamic param) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getVip,User::getIsYoung));
		if(null == user) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(1 == user.getIsYoung()) {
			return AjaxResult.error("青少年模式不可发布");
		}
		// 判断是否需要VIP
		boolean authorityStatus = priceSettingService.authorityStatus("publishDynamic");
		if(authorityStatus && 0 == user.getVip()) {
			return AjaxResult.error(500103,"请开通VIP方可报名");
		}
		if(!redisUtil.setIfAbsent("publishDynamic:"+loginUserId)) {
			return AjaxResult.error("动态正在发布中~");
		}
		try {
			param.setUserId(loginUserId);
			param.setStatus(0);
			PriceSetting one = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "动态审核开关"));
			if(null != one && 1 == one.getEnabled()) {
				param.setStatus(1);
			}
			userDynamicMapper.insert(param);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
		return AjaxResult.success();
	}

	@Override
	public AjaxResult delDynamic(AppUserDynamicVO param) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		UserDynamic dynamic = userDynamicMapper.selectOne(new LambdaQueryWrapper<UserDynamic>().eq(UserDynamic::getId, param.getId()).eq(UserDynamic::getUserId, loginUserId));
		if(null == dynamic) {
			return AjaxResult.error("数据不存在");
		}
		dynamic.setStatus(3);
		userDynamicMapper.updateById(dynamic);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult publishParty(UserParty party) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getVip,User::getIsYoung));
		if(null == user ) {
			return AjaxResult.error(50010,"请重新登录");
		}
		if(1 == user.getIsYoung()) {
			return AjaxResult.error("青少年模式不可发布");
		}
		// 判断是否需要VIP
		boolean authorityStatus = priceSettingService.authorityStatus("activityDynamic");
		if(authorityStatus && 0 == user.getVip()) {
			return AjaxResult.error(500103,"请开通VIP方发布活动");
		}
		if(!redisUtil.setIfAbsent("publishParty:"+loginUserId)) {
			return AjaxResult.error("活动在发布中~");
		}
		party.setUserId(loginUserId);
		PriceSetting one = priceSettingService.getOne(new LambdaQueryWrapper<PriceSetting>().eq(PriceSetting::getPriceType, "约玩审核开关"));
		if(null != one && 1 == one.getEnabled()) {
			party.setStatus(1);
		}
		userPartyMapper.insert(party);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult userParty(AppUserDynamicVO param) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User currUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId)
				.select(User::getId,User::getLoginPointX,User::getLoginPointY));
		if(null == currUser) {
			return AjaxResult.error(50010,"请重新登录");
		}
		try {
			param.setLoginUserId(loginUserId);
			param.setLongitude(currUser.getLoginPointX()==null?new BigDecimal("112"):currUser.getLoginPointX());
			param.setLatitude(currUser.getLoginPointY()==null?new BigDecimal("28"):currUser.getLoginPointY());
			IPage<AppParty> userParty = userPartyMapper.userParty(new Page<AppDynamic>().setCurrent(param.getPageNo()).setSize(10),param);
			List<AppParty> records = userParty.getRecords();
			records.parallelStream().forEach(dynamic ->{
				//处理关注状态
				if(null != param.getUserId()) {
					if(loginUserId.longValue() == param.getUserId().longValue()) {
						dynamic.setConcernStatus(-1);
					}
				}
				// 处理年龄
				if(null != dynamic.getBirthday()) {
					dynamic.setAge(CommonUtil.getAge(dynamic.getBirthday()));
				}else {
					dynamic.setAge(22);
				}
				// 处理距离
				dynamic.setDistanceShow((DistanceUtil.transferDistance(
						dynamic.getDistance()==null?new BigDecimal("0").doubleValue():dynamic.getDistance().doubleValue())));
				// 处理虚拟用户距离
				if(3 == dynamic.getEnabled()) {
					if(dynamic.getVirtuallyDistance() > 0) {
						dynamic.setDistanceShow(dynamic.getVirtuallyDistance()+"km");
					}else {
						dynamic.setDistanceShow(DistanceUtil.getVirtuallyDistance());
					}
				}
				dynamic.setDistanceShow("");
				//处理日期
				dynamic.setCreateTimeShow(DateUtils.getTimeCompareStringDynamic(dynamic.getCreateTime()));
				if(2 == param.getDynamicType()) {
					dynamic.setCreateTimeShow(DateUtils.getTimeCompareStringDynamicYmd(dynamic.getCreateTime()));
				}
				// 09-02 去掉约玩动态时间
				dynamic.setCreateTimeShow("");
				// 相册
				List<FileAttachment> fileList = fileAttachmentMapper.selectList(new LambdaQueryWrapper<FileAttachment>()
						.eq(FileAttachment::getFileModule, "photo").eq(FileAttachment::getUserId, dynamic.getUserId()));
				if(CollectionUtil.isNotEmpty(fileList)) {
					dynamic.setRealPersonAuth(1);
				}
			});
			taskAsync.updateUserStatus(loginUserId);
			return AjaxResult.success(CollectionUtil.isEmpty(records)?new ArrayList<AppDynamic>():records);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("网络繁忙");
		}
	}

	@Override
	public AjaxResult delParty(AppUserDynamicVO param) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		UserParty userParty = userPartyMapper.selectOne(new LambdaQueryWrapper<UserParty>().eq(UserParty::getId, param.getId()).eq(UserParty::getUserId, loginUserId));
		if(null == userParty) {
			return AjaxResult.error("数据不存在");
		}
		userParty.setStatus(3);
		userPartyMapper.updateById(userParty);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult enrollParty(UserParty party) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getVip));
		if(null == user ) {
			return AjaxResult.error(50010,"请重新登录");
		}
		// 判断是否需要VIP
		boolean authorityStatus = priceSettingService.authorityStatus("enrollActivity");
		if(authorityStatus && 0 == user.getVip()) {
			return AjaxResult.error(500103,"请开通VIP方可报名");
		}
		party = userPartyMapper.selectOne(new LambdaQueryWrapper<UserParty>().eq(UserParty::getId, party.getId()).eq(UserParty::getStatus, 0)
				.select(UserParty::getId,UserParty::getUserId,UserParty::getPartyType,UserParty::getPartyNum));
		if(null == party) return AjaxResult.error("当前约玩不存在");
		if(loginUserId.longValue() == party.getUserId().longValue()) return AjaxResult.error("不可报名自己发布的约玩");
		
		Integer count1 = userPartyEnrollMapper.selectCount(new LambdaQueryWrapper<UserPartyEnroll>().eq(UserPartyEnroll::getPartyId, party.getId()).eq(UserPartyEnroll::getUserId, loginUserId));
		if(count1 > 0) {
			return AjaxResult.error("您已报名");
		}
		Integer count = userPartyEnrollMapper.selectCount(new LambdaQueryWrapper<UserPartyEnroll>().eq(UserPartyEnroll::getPartyId, party.getId()).eq(UserPartyEnroll::getStatus, 1));
		if(count >= party.getPartyNum()) {
			return AjaxResult.error("报名人数已满");
		}
		UserPartyEnroll userPartyEnroll = new UserPartyEnroll();
		userPartyEnroll.setPartyId(party.getId());
		userPartyEnroll.setUserId(loginUserId);
		userPartyEnrollMapper.insert(userPartyEnroll);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult promptlyParty(Integer partyType, Integer pageNo) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		System.out.println("当前登录的ID："+loginUserId);
		IPage<UserParty> promptlyParty = userPartyMapper.promptlyParty(new Page<UserParty>().setCurrent(pageNo).setSize(10), partyType, loginUserId);
		List<UserParty> list = promptlyParty.getRecords();
		list.stream().forEach(party ->{
			if(null != party.getCreateTime()) {
				party.setCreateTimeShow(DateUtils.format(party.getCreateTime(), "yyyy-MM-dd"));
			}
			// 处理状态  0=待接受 1=已接受 2=已拒绝 3=已过期 4=同意、拒绝的按钮
			if(0 == party.getTimeType() && StringUtils.isNotEmpty(party.getEndTime())) {
				Date endTime = DateUtils.stringToDate(party.getEndTime(), "yyyy-MM-dd HH:mm");
				if(endTime.before(new Date())) {
					party.setStatus(3);
				}
			}
			if(3 != party.getStatus()) { // 不是已过期 则处理状态
				if(loginUserId.longValue() == party.getPubUserId().longValue() && 0 == party.getStatus()) {
					party.setStatus(4);
				}
			}
		});
		//		Page<UserParty> page = userPartyMapper.selectPage(new Page<UserParty>().setCurrent(pageNo).setSize(10), new LambdaQueryWrapper<UserParty>().eq(UserParty::getStatus, 0).eq(UserParty::getPartyType, partyType)
		//				.orderByDesc(UserParty::getCreateTime));
		//		List<UserParty> list = page.getRecords();
		//		list.stream().forEach(party ->{
		//			if(1 == partyType) { // 双人约玩
		//				// 取出状态
		//				if(loginUserId.longValue() == party.getUserId().longValue()) {
		//					party.setPartyStatus(3);
		//				}
		//				UserPartyEnroll enroll = userPartyEnrollMapper.selectOne(new LambdaQueryWrapper<UserPartyEnroll>().eq(UserPartyEnroll::getPartyId, party.getId()));
		//				if(null != enroll) {
		//					party.setPartyStatus(enroll.getStatus());
		//				}
		//				if(null != party.getCreateTime()) {
		//					party.setCreateTimeShow(DateUtils.format(party.getCreateTime(), "yyyy-MM-dd"));
		//				}
		//			}
		//		});
		return AjaxResult.success(CollectionUtil.isNotEmpty(list)?list:new ArrayList<UserParty>());
	}

	@Override
	public AjaxResult partyOperate(UserParty party) {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		UserParty userParty = userPartyMapper.selectOne(new LambdaQueryWrapper<UserParty>().eq(UserParty::getId, party.getId()).eq(UserParty::getUserId, loginUserId)
				.select(UserParty::getId,UserParty::getUserId,UserParty::getPartyType));
		if(null == userParty) {
			return AjaxResult.error("派对不存在");
		}
		UserPartyEnroll enroll = userPartyEnrollMapper.selectOne(new LambdaQueryWrapper<UserPartyEnroll>().eq(UserPartyEnroll::getUserId, party.getUserId()).eq(UserPartyEnroll::getPartyId, party.getId()));
		if(null == enroll) {
			return AjaxResult.error("派对成员有误");
		}
		enroll.setStatus(party.getType());
		enroll.setUpdateTime(new Date());
		userPartyEnrollMapper.updateById(enroll);
		return AjaxResult.success();
	}

	@Override
	public AjaxResult publishAuthControl() {
		Long loginUserId = getUserId();
		if(null == loginUserId) {
			return AjaxResult.error(50010,"请重新登录");
		}
		User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, loginUserId).select(User::getId,User::getVip));
		if(null == user) {
			return AjaxResult.error(50010,"请重新登录");
		}
		Map<String,Object> map = new HashMap<String,Object>();
		if(1 == user.getVip()) {
			map.put("publishDynamic", 0);
			map.put("activityDynamic", 0);
			map.put("enrollActivity", 0);
		}else {
			List<String> types = new ArrayList<String>();
			types.add("publishDynamic");types.add("activityDynamic");types.add("enrollActivity");
			List<PriceSetting> list = priceSettingService.list(new LambdaQueryWrapper<PriceSetting>().in(PriceSetting::getPriceType, types)
					.select(PriceSetting::getId,PriceSetting::getEnabled,PriceSetting::getPriceType));
			map.put("publishDynamic", 0);
			map.put("activityDynamic", 0);
			map.put("enrollActivity", 0);
			if(CollectionUtil.isNotEmpty(list)) {
				list.stream().forEach(a ->{
					map.put(a.getPriceType(), a.getEnabled());
				});
			}
		}
		return AjaxResult.success(map);
	}
}
